package Coffee.util;


import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Cbase {
    public int update(String sql, Object... objects) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int i = 0;
        try {
            conn = jdbcUtil.getConnection();
            pstmt = jdbcUtil.getPstmt(conn, sql, objects);
            i = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            jdbcUtil.close(conn, pstmt, null);
        }

        return i;
    }
    public <T> T getOne(Class<T> cls,String sql,Object... objects){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        T t = null;
        try {
            conn = jdbcUtil.getConnection();
            pstmt = jdbcUtil.getPstmt(conn, sql,objects);
            rs = pstmt.executeQuery();
            if (!rs.next()){
                return null;
            }
            t = cls.newInstance(); //通过反射创建泛型对象
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount(); //所有的列数
            //这个循环是根据不同的类型的字段的个数，获取字段的名称，和字段值，完成
            //对象数据的动态绑定
            for (int i = 1; i <= columnCount; i++) {
                //通过BeanUtils绑定对象数据，传入的参数是对象、字段名、字段对应的值
                BeanUtils.setProperty(t,metaData.getColumnLabel(i).toLowerCase(),
                        rs.getObject(i));
            }
            return t;
        }  catch (Exception e) {
            e.printStackTrace();
        } finally {
            jdbcUtil.close(conn,pstmt,rs);
        }
        return null;
    }


    public <T> List<T> getAll(Class<T> cls, String sql, Object... objects) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<T> resultList = new ArrayList<>();
        try {
            conn = jdbcUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < objects.length; i++) {
                pstmt.setObject(i + 1, objects[i]);
            }
            rs = pstmt.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            while (rs.next()) {
                T t = cls.newInstance(); // 通过反射创建泛型对象
                for (int i = 1; i <= columnCount; i++) {
                    // 通过BeanUtils绑定对象数据，传入的参数是对象、字段名、字段对应的值
                    BeanUtils.setProperty(t, metaData.getColumnLabel(i).toLowerCase(), rs.getObject(i));
                }
                resultList.add(t);
            }
            return resultList;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jdbcUtil.close(conn, pstmt, rs);
        }
        return null;
    }
}







